import React, {Component} from 'react';
import {AppRegistry, TouchableHighlightBase} from 'react-native';
import DiaryList from './DiaryList';
import DiaryReader from './DiaryReader';
import DiaryWriter from './DiaryWriter';
import RealmHelper from './RealmHelper';
var uuid = require('react-native-uuid');
export default class Diary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uiCode: 1,
      diaryList: [],
    };
    //执行回调函数绑定操作
    this.bindAllMyFunction();
  }
  bindAllMyFunction() {
    this.selectListItem = this.selectListItem.bind(this);
    this.writeDiary = this.writeDiary.bind(this);
    this.returnPressed = this.returnPressed.bind(this);
    this.saveDiaryAndReturn = this.saveDiaryAndReturn.bind(this);
    this.searchKeyword = this.searchKeyword.bind(this);
  }
  //阅读日记界面、写界面返回日记列表的处理函数
  returnPressed() {
    this.setState({uiCode: 1});
  }
  //写日记并返回的处理
  saveDiaryAndReturn(newDiaryMood, newDiaryBody, newDiaryTitle) {
    const newId = uuid.v1();
    newDiaryBody = newDiaryBody || '';
    newDiaryTitle = newDiaryTitle || '';
    console.log('id:', newId);
    RealmHelper.saveDiary(newId, newDiaryMood, newDiaryBody, newDiaryTitle);
  }
  deleteItem(id) {
    console.log('delete_id:', id);
    RealmHelper.deleteDiary(id);
  }
  //写日记按钮处理
  writeDiary() {
    this.setState(() => {
      return {uiCode: 3};
    });
  }
  searchKeyword(keyword) {
    console.log('you searched :{0}', keyword);
  }
  //日记列表选中某条操作
  selectListItem() {
    this.setState({uiCode: 2});
  }
  componentDidMount() {
    this.setState({
      diaryList: RealmHelper.getAllDiary(),
    });
  }
  showDiaryList() {
    return (
      <DiaryList
        selectListItem={this.selectListItem}
        searchKeyword={this.selectListItem}
        writeDiary={this.writeDiary}
        diaryList={this.state.diaryList}
        deleteItem={this.deleteItem}
      />
    );
  }
  showDiaryReader() {
    return (
      <DiaryReader
        returnToDiaryList={this.returnPressed}
        diaryTitle={this.state.diaryTitle}
        diaryBody={this.state.diaryBody}
        diaryTime={this.state.diaryTime}
        readingPreviousPressed={this.readingPreviousPressed}
        readingNextPressed={this.readingNextPressed}
        returnPressed={this.returnPressed}
      />
    );
  }
  showDiaryWriter() {
    return (
      <DiaryWriter
        returnPressed={this.returnPressed}
        saveDiary={this.saveDiaryAndReturn}
      />
    );
  }
  render() {
    if (this.state.uiCode === 1) return this.showDiaryList();
    if (this.state.uiCode === 2) return this.showDiaryReader();
    if (this.state.uiCode === 3) return this.showDiaryWriter();
  }
}
AppRegistry.registerComponent('Diary', () => App);
